/***************************************************************************************
  *Copyright(C),2010-2016,Sumscope
  *FileName   : SortTask.cpp
  *Author     : scofined.qi
  *Version    : 1.0
  *Date       : 2016/06/03
  *Desc       : //用于说明此程序文件完成的主要功能
  *Relation   :
  *Other      : //其他内容说明
  *Function   : //主要函数列表，每条记录应包含函数名及功能简要说明
  *History    : //修改历史纪录列表，每条修改记录应包含修改日期，修改者以及修改内容简介
  ***************************************************************************************/

#include "SortTask.h"
#include <core/time/time.h>
#include <QThread>

using namespace qb::base;
namespace qb{
	namespace ht{
		SortTask::SortTask(ThreadSorter* ts, char* b, int w, unsigned int p, unsigned int r, FuncCompColumn comp) :
			sorter(ts), base(b), width(w), left(p), right(r), comp_func(comp)
		{
			finished = false;
		}

		void SortTask::Init(ThreadSorter* ts, char* b, int w, unsigned int p, unsigned int r, FuncCompColumn comp)
		{
			sorter = ts;
			base = b;
			width = w;
			left = p;
			right = r;
			comp_func = comp;
			finished = false;
			timepoints[kTaskTimeCommit] = HighResTime();
		}

		TaskCache::TaskCache()
		{

		}

		TaskCache::~TaskCache()
		{

		}

		SortTask* TaskCache::GetTask(ThreadSorter* ts, char* base, int w, int l, int r, FuncCompColumn comp)
		{
			int taskid = m_used_count;
			SortTask* task = taskid < THREAD_CACHE_SIZE ? (&m_stack[m_used_count++]) : (new SortTask());
			task->Init(ts, base, w, l, r, comp);
			task->taskid = taskid;
			return task;
		}

		void TaskCache::AddWaitTask(SortTask* task, bool first)
		{
			m_tasks.push_back(task);
			if (first)
				m_first_task = task;
		}

		void TaskCache::Reset()
		{
			m_used_count = 0;
			memset(m_stack, 0, THREAD_CACHE_SIZE*sizeof(SortTask));
			m_tasks.clear();
			m_first_task = 0;
		}

		void TaskCache::WaitAllFinish()
		{
			// 等待后台所有线程结束完毕,后续可以更高效
			int ntask = m_tasks.size();
			int count = 0;
			while (count >= ntask)
			{
				count = 0;
				for (int i = 0; i < ntask; i++)
				{
					count += m_tasks[i]->finished ? 1 : 0;
				}
                QThread::msleep(1);
			}


			//Report();
			for (int i = 0; i < ntask; i++)
			{
				SortTask* task = m_tasks.at(i);
				if (task < m_stack && task >= m_stack + THREAD_CACHE_SIZE)
					delete task;
			}
			m_tasks.clear();
		}

		void TaskCache::Report()
		{

		}
	}
}//namespace qb
